package rjeutsky.servlets;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import rjeutsky.ControllerWrapper;
import rjeutsky.models.User;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/Login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String login = request.getParameter("login");
		String password = request.getParameter("password");
		User user = ControllerWrapper.getApplicationController().getUser(login,
				password);
		request.getSession().setAttribute("currentUser", user);
		if (user == null) {
			response.sendRedirect("Login.jsp?invalid=true");
		} else {
			updateCookies(request, response);
			response.sendRedirect("Default.jsp");
		}
	}

	private void updateCookies(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		Date currentTime = new Date();
		int visited = 0;
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if ("visited".equals(cookie.getName())) {
					String visitedTimes = cookie.getValue();

					try {
						visited = Integer.parseInt(visitedTimes);
					} catch (Exception e) {

					}
					break;
				}
			}
		}
		
		visited++;
		Cookie dateCookie = new Cookie("lastVisit", currentTime.toString());
		response.addCookie(dateCookie);
		Cookie visitedCookie = new Cookie("visited", "" + visited);
		response.addCookie(visitedCookie);
	}
}
